import json
import os
import stat
import mimetypes
import time

from ipython_genutils import py3compat


def list_dir(path, res, username):
    # 获取当前文件夹状态
    res = get_status(path, res)
    for i in os.listdir(path):
        temp_dir = os.path.join(path, i)
        if not res["content"]:
            res["content"] = []
        if not i.startswith('.') and "@" in i:
            if os.path.isdir(temp_dir):
                file_names = i.split("@")
                file_name = file_names.pop(-1)
                file_name_ = file_name.split(username).pop(-1)
                if file_name.replace(username, "!@#$%^&*").replace(file_name_, "").replace("!@#$%^&*",
                                                                                           username) == username:
                    temp = {"name": "@".join(file_names) + file_name_,
                            "path": i, "last_modified": "", "created": "",
                            "content": None, "format": None,
                            "mimetype": None, "size": None, "writable": True, "type": "directory"}
                    file_info = get_status(temp_dir, temp)
                    res['content'].append(file_info)
            else:
                file_name = i.split(".")
                file_fix = ""
                if os.path.isfile(os.path.join(py3compat.getcwd(), 'WorkFiles' + i)) and "." in i:
                    file_fix = "." + file_name.pop(-1)
                file_names = ".".join(filter(None, file_name)).split("@")
                file_name = file_names.pop(-1)
                file_name_ = file_name.split(username).pop(-1)
                if file_name.replace(username, "!@#$%^&*").replace(file_name_, "").replace(
                        "!@#$%^&*", username) == username:
                    temp = {"name": "@".join(file_names) + file_name_ + file_fix, "path": i, "last_modified": "",
                            "created": "", "content": None, "format": None,
                            "mimetype": None, "size": None, "writable": True, "type": "file"}
                    file_info = get_status(temp_dir, temp)
                    res['content'].append(file_info)
    return res


def get_config_dirs(path, username):
    res = {"name": "", "path": "", "last_modified": "", "created": "", "content": None, "format": "json",
           "mimetype": None, "size": None, "writable": True, "type": "directory"}
    return list_dir(path, res, username)  # 输入路径


def get_status(path, res):
    """
    获取文件状态
    :param path: 路径
    :return: 返回文件/文件夹状态
    """
    file_stats = os.stat(path)
    res["last_modified"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(file_stats[stat.ST_MTIME]))
    res["created"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(file_stats[stat.ST_CTIME]))
    res["mimetype"] = mimetypes.guess_type(path)[0]
    res["size"] = file_stats[stat.ST_SIZE]
    return res


if __name__ == '__main__':
    print(get_config_dirs("WorkFiles", "zhxcs001"))
